import type { FormSchema } from '@/components/core/schema-form/';
import { dictPotionsListApi } from '@/api/workorder/select';
import { formatCategary2Tree, formatDept2Tree } from '@/core/permission/utils';
import { getCategaryList } from '@/api/workorder/categary';
import { InboxOutlined } from '@ant-design/icons-vue';
import { downloadAttament, deleteAttament } from '@/api/workorder/common/attachment';
import { reactive } from 'vue';
import { uploadAttamentOne } from '../common/common';
import { getDeptList } from '@/api/system/dept';
import { message } from 'ant-design-vue';

// import { useUserStore } from '@/store/modules/user';

// 当前页面使用的数据
export let uploadFileObject = reactive({
  uploadFileList: [],
  defaultFileList: [],
});

const fetchOptionList = async (params: any) => {
  const data = await dictPotionsListApi(params);
  return data.map((item) => ({
    label: item.name,
    value: item.code,
  }));
};

const loadCategaryData = async (params: any) => {
  let data = await getCategaryList(params);
  return formatCategary2Tree(data, '0');
};

export const workorderschemas: FormSchema[] = [
  {
    field: 'workOrderStatus',
    component: 'Input',
    colProps: {
      span: 0,
    },
    defaultValue: '0',
    componentProps: {
      hidden: true,
    },
  },
  {
    field: 'id',
    component: 'Input',
    colProps: {
      span: 0,
    },
    componentProps: {
      hidden: true,
    },
  },
  {
    field: 'latitude',
    component: 'Input',
    colProps: {
      span: 0,
    },
    componentProps: {
      hidden: true,
    },
  },
  {
    field: 'longitude',
    component: 'Input',
    colProps: {
      span: 0,
    },
    componentProps: {
      hidden: true,
    },
  },
  {
    field: 'extOrderNumber',
    component: 'Input',
    colProps: {
      span: 0,
    },
    componentProps: {
      hidden: true,
    },
  },
  {
    field: 'workOrderNumber',
    component: 'Input',
    label: '工单编号',
    colProps: {
      span: 6,
    },
    componentProps: {
      disabled: true,
      clearIcon: false,
    },
  },
  {
    field: 'acceptNumber',
    component: 'Input',
    label: '受理工号',
    colProps: {
      span: 6,
    },
    componentProps: {
      disabled: true,
    },
  },
  {
    field: 'acceptTime',
    component: 'DatePicker',
    label: '受理时间',
    colProps: {
      span: 6,
    },
    componentProps: {
      style: {
        width: '100%',
      },
      disabled: true,
      showTime: true,
    },
  },
  {
    field: 'callerNumber',
    component: 'Input',
    label: '来电号码',
    componentProps: {},
    rules: [
      {
        required: false,
        type: 'string',
        validator: (_, value) => {
          let regPhone = /^[1][3,4,5,7,8][0-9]{9}$/;
          let regTel = /^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$/;
          const isError = !(regPhone.test(value) || regTel.test(value));
          if (isError) {
            return Promise.reject('请输入正确的手机号码或固话号码');
          } else {
            return Promise.resolve();
          }
        },
      },
      { max: 13, message: '来电号码不能大于13个字符' },
    ],
    colProps: {
      span: 6,
    },
  },
  {
    field: 'workOrderType',
    component: 'Select',
    label: '工单类型',
    rules: [{ required: true, type: 'string' }],
    colProps: {
      span: 6,
    },
    componentProps: {
      request: async () => {
        return await fetchOptionList({ code: 'workorder_type' });
      },
    },
  },
  {
    field: 'infoSerrces',
    component: 'Select',
    label: '信息来源',
    rules: [{ required: true, type: 'string' }],
    colProps: {
      span: 6,
    },
    componentProps: {
      request: async () => {
        return await fetchOptionList({ code: 'info_serrces' });
      },
    },
  },
  {
    field: 'region',
    component: 'Select',
    label: '所在区域',
    rules: [{ required: true, type: 'string' }],
    colProps: {
      span: 6,
    },
    componentProps: {
      request: async () => {
        return await fetchOptionList({ code: 'region' });
      },
    },
  },
  {
    field: 'industryType',
    component: 'TreeSelect',
    label: '行业类型',
    rules: [{ required: true, type: 'string' }],
    colProps: {
      span: 6,
    },
    componentProps: {
      fieldNames: {
        label: 'name',
        value: 'id',
      },
      colProps: {
        span: 12,
      },
      request: async () => {
        return await loadCategaryData({ sysCode: 'workorder', categaryCode: 'industry_type' });
      },
      getPopupContainer: () => document.body,
    },
  },
  {
    field: 'responsibleUnit',
    component: 'TreeSelect',
    label: '责任单位',
    rules: [{ required: true, type: 'string' }],
    colProps: {
      span: 6,
    },
    componentProps: {
      filterTreeNode: true,
      treeNodeFilterProp: 'name',
      treeDefaultExpandAll: true,
      request: async () => {
        return formatDept2Tree(await getDeptList());
      },
    },
  },
  {
    field: 'area',
    component: 'Select',
    label: '所在片区',
    rules: [{ required: true, type: 'string' }],
    colProps: {
      span: 6,
    },
    componentProps: {
      request: async () => {
        return await fetchOptionList({ code: 'area' });
      },
    },
  },
  {
    field: 'contacts',
    component: 'Input',
    label: '联系人',
    componentProps: {},
    rules: [
      { required: true, type: 'string' },
      { max: 20, message: '联系人不能大于10个字' },
    ],
    colProps: {
      span: 6,
    },
  },
  {
    field: 'contactsInfo',
    component: 'Input',
    label: '联系方式',
    componentProps: {},
    rules: [{ required: true, type: 'string' }],
    colProps: {
      span: 6,
    },
  },
  {
    field: 'dispatchTime',
    component: 'Input',
    label: '派单时间',
    componentProps: {},
    vShow: ({ formModel }) => {
      return formModel.workOrderStatus != 0;
    },
    colProps: {
      span: 6,
    },
  },
  {
    field: 'expirationTime',
    component: 'Input',
    label: '到期时间',
    componentProps: {},
    vShow: ({ formModel }) => {
      return formModel.workOrderStatus != 0;
    },
    colProps: {
      span: 6,
    },
  },
  {
    field: 'completionTime',
    component: 'Input',
    label: '结案时间',
    componentProps: {},
    vShow: ({ formModel }) => {
      return formModel.workOrderStatus == 5;
    },
    colProps: {
      span: 6,
    },
  },
  {
    field: 'divider-basic-01',
    component: 'CountDown',
    label: '回复剩余时间',
    componentProps: ({ formModel }) => ({
      title: '',
      countdown: new Date(formModel.expirationTime).getTime(),
      format: ' D 天 H 时 m 分 s 秒',
      autoStart: true,
      start: new Date(formModel.expirationTime).getTime(),
    }),
    vShow: ({ formModel }) => {
      return formModel.workOrderStatus != 0 && formModel.workOrderStatus != 5;
    },
    colProps: {
      span: 12,
    },
  },
  {
    field: 'processingPeriod',
    component: 'InputNumber',
    label: '处理期限',
    rules: [{ required: true, type: 'string' }],
    componentProps: {
      addonAfter: '小时',
      min: 0,
      style: {
        width: '100%',
      },
    },
    colProps: {
      span: 6,
    },
    defaultValue: 24,
  },
  {
    field: 'urgency',
    component: 'RadioGroup',
    label: '紧急程度',
    colProps: {
      span: 6,
    },
    defaultValue: '0',
    componentProps: {
      options: [
        {
          label: '一般',
          value: '0',
        },
        {
          label: '紧急',
          value: '2',
        },
      ],
    },
  },
  {
    field: 'returnVisit',
    component: 'RadioGroup',
    label: '是否回访',
    colProps: {
      span: 6,
    },
    defaultValue: '1',
    componentProps: {
      options: [
        {
          label: '是',
          value: '1',
        },
        {
          label: '否',
          value: '2',
        },
      ],
    },
  },
  {
    field: 'occAddress',
    component: 'InputTextArea',
    label: '发生地址',
    componentProps: {
      rows: 1,
    },
    colProps: {
      span: 24,
    },
    rules: [
      { required: false, type: 'string' },
      { max: 200, message: '发生地址不能大于100个字' },
    ],
  },
  {
    field: 'problemDesc',
    component: 'InputTextArea',
    label: '问题描述',
    colProps: {
      span: 24,
    },
    componentProps: {
      rows: 5,
    },
    rules: [
      { required: false, type: 'string' },
      { max: 5000, message: '问题描述不能大于500个字' },
    ],
  },
  {
    field: 'remarks',
    component: 'InputTextArea',
    label: '备注',
    colProps: {
      span: 24,
    },
    componentProps: {
      rows: 3,
    },
    rules: [
      { required: false, type: 'string' },
      { max: 5000, message: '备注不能大于500个字' },
    ],
  },
  {
    field: 'attament',
    component: 'UploadDragger',
    label: '附件',
    colProps: {
      span: 24,
    },
    componentProps: ({ formInstance }) => ({
      beforeUpload: async (file: any) => {
        // 新增加处理直接返回false
        if (formInstance?.getFieldsValue().id) {
          // 进行文件上传处理
          uploadAttamentOne(file, 'workorder', formInstance?.getFieldsValue().id);
        }
        return false;
      },
      onRemove: (file: any) => {
        deleteAttament(file.uid);
        return true;
      },
      onChange: async (fileList: any) => {
        uploadFileObject.uploadFileList = fileList.fileList;
        if (formInstance?.getFieldsValue().id) {
          formInstance?.updateSchema({
            field: 'attament',
            componentProps: {
              fileList: fileList.fileList,
            },
          });
        }
      },
      showUploadList: {
        showDownloadIcon: true,
        showRemoveIcon: true,
        showPreviewIcon: true,
      },
      onDownload: (file) => {
        // 文件下载
        downloadAttament(file.uid);
      },
    }),
    componentSlots: {
      default: () => (
        <div>
          <p>
            <InboxOutlined />
          </p>
          <p style={'color:blue'}>将文件拖到此处或点击上传</p>
        </div>
      ),
    },
  },
];

export const moresendsschemas: FormSchema[] = [
  {
    field: 'mainDept',
    component: 'Input',
    componentProps: {
      hidden: true,
    },
    colProps: {
      span: 0,
    },
  },
  {
    field: 'depts',
    component: 'TreeSelect',
    label: '多单位',
    required: true,
    componentProps: ({ formModel }) => ({
      placeholder: '请选择责任单位',
      showSearch: true,
      request: async () => {
        return formatDept2Tree(await getDeptList());
      },
      onSelect: (value) => {
        // if (formModel.mainDept == value) {
        //   message.error('责任单位已选中，不可再次选择！');
        //   formModel.depts.pop();
        // }
        // return false;
      },
      multiple: true,
      filterTreeNode: true,
      treeNodeFilterProp: 'name',
      treeDefaultExpandAll: true,
    }),
  },
  {
    field: 'timeOut',
    component: 'Select',
    label: '子单处理期限',
    colProps: {
      span: 20,
    },
    defaultValue: '24',
    componentProps: {
      options: [
        {
          label: '12',
          value: '12',
        },
        {
          label: '24',
          value: '24',
        },
        {
          label: '36',
          value: '36',
        },
        {
          label: '48',
          value: '48',
        },
        {
          label: '72',
          value: '72',
        },
        {
          label: '96',
          value: '96',
        },
      ],
    },
  },
  {
    field: 'divider-basic',
    component: 'Divider',
    label: '小时(h)',
    componentProps: {
      type: 'vertical',
    },
    colProps: {
      span: 4,
    },
  },
];

export const sendlastschemas: FormSchema[] = [
  {
    field: 'mainDept',
    component: 'Input',
    componentProps: {
      hidden: true,
    },
    colProps: {
      span: 0,
    },
  },
  {
    field: 'workOrderStatus',
    component: 'Input',
    componentProps: {
      hidden: true,
    },
    colProps: {
      span: 0,
    },
  },
  {
    field: 'dept',
    component: 'TreeSelect',
    label: '转派单位',
    required: true,
    componentProps: ({ formModel }) => ({
      placeholder: '请选择转派单位',
      showSearch: true,
      request: async () => {
        // const userStore = useUserStore();
        // console.log( userStore.userInfo.user?.org.id, );
        let parentId = formModel.mainDept;
        if (['2', '9'].indexOf(formModel.workOrderStatus) > -1) {
          parentId = null;
        }
        return formatDept2Tree(await getDeptList(), parentId);
      },
      onSelect: (value) => {
        if (formModel.mainDept == value) {
          message.error('责任单位已选中，不可再次选择！');
          formModel.depts.pop();
        }
        return false;
      },
      filterTreeNode: true,
      treeNodeFilterProp: 'name',
      treeDefaultExpandAll: true,
    }),
  },
];
